package com.cq.hd.admin.biz;

import com.cq.hd.admin.po.TbAdminUserPo;
import com.cq.hd.admin.po.TbBusinessAdminUserPo;
import com.cq.hd.admin.service.TbAdminUserService;
import com.cq.hd.admin.vo.AdminBusinessInfoVo;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.order.api.TbOrderSettleBillApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
@Slf4j
public class AdminBusinessBiz {

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderSettleBillApi orderSettleBillApi;

    @Autowired
    private TbAdminUserService adminUserService;

    public AdminBusinessInfoVo businessInfo(TbBusinessAdminUserPo businessAdminUserPo) {
        AdminBusinessInfoVo adminBusinessInfoVo = new AdminBusinessInfoVo();

        BusinessVo businessVo = businessApi.getActiveCount(businessAdminUserPo.getAppUserId(), businessAdminUserPo.getBusinessId()).unpack();
        if (businessVo == null) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }
        BeanUtils.copyProperties(businessVo, adminBusinessInfoVo);

        TbAdminUserPo adminUserPo = adminUserService.getById(businessAdminUserPo.getAdminUserId());
        if (adminUserPo == null) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }
        adminBusinessInfoVo.setLastLoginTime(adminUserPo.getLastLoginTime());

        // 待支付补贴金额
        BigDecimal subsidyAmt = businessVo.getSubsidyAmt();
        BigDecimal waitPayAmt = orderSettleBillApi.getBusinessWaitPaySubsidyAmt(businessVo.getId()).unpack();
        BigDecimal waitRechargeAmt = BigDecimal.ZERO;
        if (waitPayAmt != null && waitPayAmt.compareTo(BigDecimal.ZERO) > 0) {
            // 保留两位，舍去第三位
            BigDecimal feeAmt = waitPayAmt.multiply(Constant.BANK_PAY_FEE_AMT_RATE).setScale(2, BigDecimal.ROUND_DOWN);
            BigDecimal invoiceAmt = waitPayAmt.multiply(Constant.BANK_PAY_INVOICE_AMT_RATE).setScale(2, BigDecimal.ROUND_DOWN);
            waitPayAmt = waitPayAmt.add(feeAmt).add(invoiceAmt).setScale(2, BigDecimal.ROUND_DOWN);

            // 待充值补贴金额 = 待支付补贴金额 - 商家补贴余额
            waitRechargeAmt = waitPayAmt.subtract(subsidyAmt).max(BigDecimal.ZERO);
        }
        adminBusinessInfoVo.setWaitPaySubsidyAmt(waitPayAmt);
        adminBusinessInfoVo.setWaitRechargeSubsidyAmt(waitRechargeAmt);

        return adminBusinessInfoVo;
    }
}
